﻿using System;
using System.Collections.Generic;

namespace MediatorPattern;

// 中介者接口
public interface IMediator
{
    void Send(string message, NetworkDevice device);
    void Register(INetworkDevice device);
}

// 具体的中介者 - 交换机
public class Switch : IMediator
{
    private readonly List<INetworkDevice> _devices = [];

    public void Register(INetworkDevice device)
    {
        _devices.Add(device);
        device.SetMediator(this);
    }

    public void Send(string message, NetworkDevice device)
    {
        foreach (var otherDevice in _devices)
        {
            if (otherDevice != device) // 不要发送给发送者
            {
                otherDevice.Receive(message);
            }
        }
    }
}

// 同事类接口
public interface INetworkDevice
{
    void Send(string message);
    void Receive(string message);
    void SetMediator(IMediator mediator);
}

// 具体的同事类 - 网络设备
public class NetworkDevice(string name) : INetworkDevice
{
    private IMediator _mediator;

    public void Send(string message)
    {
        _mediator.Send(message, this);
    }

    public void Receive(string message)
    {
        Console.WriteLine($"Device\"{name}\" received message: {message}");
    }

    public void SetMediator(IMediator mediator)
    {
        _mediator = mediator;
    }
}

public static class Program
{
    public static void Main()
    {
        // 创建中介者 - 交换机
        IMediator switchMediator = new Switch();

        // 创建网络设备
        INetworkDevice device1 = new NetworkDevice("device1");
        INetworkDevice device2 = new NetworkDevice("device2");
        INetworkDevice device3 = new NetworkDevice("device3");

        // 注册设备到交换机
        switchMediator.Register(device1);
        switchMediator.Register(device2);
        switchMediator.Register(device3);

        // 设备1发送消息
        device1.Send("Hello from Device 1!");

        // 设备2发送消息
        device2.Send("Hello from Device 2!");
    }
}